<?php
namespace app\common\model\user;

use app\common\model\BaseModel;

/**
 * 用户余额变动明细模型
 */
class UserWithdrawal extends BaseModel
{
    protected $pk = 'id';
    public function user()
    {
        return $this->belongsTo(User::Class,'user_id')->field('user_id,mobile,nickName');
    }
//    public function bank()
//    {
//        return $this->belongsTo(BankCard::Class);
//    }
    public function get_list($data)
    {
        $where[] = ['is_delete','=','0'];
        if(isset($data['user_id']))
        {
            $where[] = ['user_id','=',$data['user_id']];
        }
        if(isset($data['date'])){
            if($data['date']){
                $stime = strtotime($data['date'][0].' 00:00:00');
                $etime = strtotime($data['date'][1].' 23:59:59');
                $where[] = ['create_time','between',[$stime,$etime]];
            }

        }

        $res = $this->with(['user'])->where($where)->paginate($data,false);
        //dump($this->getLastSql());die;
        return $res;
    }
    //添加记录
    public function add($data,$user)
    {

        //计算余额
        if($user['balance']<$data['money'])
        {
            $this->error = '余额不足！';
            return false;
        }
        $bank_model = new BankCard();
        $bank = $bank_model->where(array("id"=>$data['bank_id']))->find();
        $data['bank_name'] = $bank['name'];
        $data['bank_uname'] = $bank['bank_uname'];
        $data['bank_number'] = $bank['bank_code'];
        $data['type'] = $bank['bank_type'];
        //扣除余额
        $user_model = new User();
        $money = $user['balance']-$data['money'];
        $user_model->where(array('user_id'=>$user['user_id']))->update(array('balance'=>$money));
        //添加提现记录
        $data['user_id'] = $user['user_id'];
        unset($data['token']);
        unset($data['bank_id']);
        $res = $this->save($data);

        return $res;
    }
    public function details($id)
    {
        return $this->with(['user'])->where(array('id'=>$id))->find();
    }

    public function edit($data)
    {
        //驳回
        if($data['info']['status'] == 2){
            //资金返还
            $user_model = new User();
            $user = $user_model->where(array("user_id"=>$data['info']['user_id']))->find();
            $balance = $user['balance']+$data['info']['money'];
            $user_model->where(array('user_id'=>$user['user_id']))->update(array('balance'=>$balance));

            $sldata = array(
                'status'=>$data['info']['status'],
                'update_time'=>time(),
                'remark'=>$data['info']['remark']
            );
            $res = $this->where(array('id'=>$data['id']))->save($sldata);
            return $res;
        }
    }
}